package bing.xu.demo;





import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;


import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;





import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;

import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {
	private EditText userNameEditText;

 
 

	private Handler handler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);

		TextView titleTextView = (TextView) findViewById(R.id.title);
		titleTextView.setText("Integrated Control System");

		

	
		
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor = settings.edit();
		if (!settings.contains("REMEMBER_USER")) {
			editor.putBoolean("REMEMBER_USER", true);
		}
		
		editor.commit();
		String userName = settings.getString("webip", "");
		

		userNameEditText = (EditText) findViewById(R.id.username_edit);
		userNameEditText.setText(userName);
	

		
		Button button = (Button) findViewById(R.id.signin_button);
		button.setOnClickListener(this);

		Button exitbutton = (Button) findViewById(R.id.exit_button);
		exitbutton.setOnClickListener(this);
	
		
			
		
	}

	public void showSuccessToast() {
		handler.post(new Runnable() {
			public void run() {
				Toast.makeText(getApplicationContext(), "OK.",
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void showFailedToast() { 
		handler.post(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), "Please check ip",
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	@Override
	public void onClick(View view) {

		
		if (view.getId() == R.id.signin_button) {

			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(this);
			String userid = settings.getString("webip", "");
			

			final String newUserName = userNameEditText.getText().toString();
			

			SharedPreferences.Editor editor = settings.edit();
			boolean flag = false;
			if (!newUserName.equals(userid)) {
				editor.putString("webip", newUserName);
				flag = true;
			}
			
			if (flag) {
				editor.commit();
			}

			// login
			final ProgressDialog pdialog = new ProgressDialog(this);
			pdialog.setMessage("登陆中...");
			// pdialog.setMax(1);
			// pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pdialog.show();

			Thread th = new Thread() {
				@Override
				public void run() {
				
					
					boolean result = login(newUserName);
					if (!result) {
						showFailedToast();
					} else {
						// showSuccessToast();
						Intent intent = new Intent();
						intent.setClassName("bing.xu.demo",
								"bing.xu.demo.WebviewdemoActivity");
					
						intent.putExtra("webip", newUserName);
						startActivity(intent);
					}
					pdialog.cancel();
				}
			};
			th.start();
		} else if (view.getId() == R.id.exit_button) {
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}

	

	protected boolean login(String newUserName) {
		  return true;

	/*	String url = "http://"+newUserName+"/cgi-bin/tv_control.cgi?name=ask";
	
		
		
		 try  
		    {  
		        HttpGet method = new HttpGet( url ); 
		       
		  
		        DefaultHttpClient client = new DefaultHttpClient();  
		        
		        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);  
		        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
		       
                        HttpResponse response =client.execute(method); 
                       
		       
		        int status = response.getStatusLine().getStatusCode();  
		        if ( status != HttpStatus.SC_OK )  {
		           // throw new Exception( "" );  
		            return false;
		        }
		          
		        String content = EntityUtils.toString( response.getEntity(), "UTF-8" ); 
		        if (content.contains("ask")) {
		        	return true;
					
				} else {
					return false;
				}
		    }  
		    catch ( Exception e )  
		    {  
		        return false;   
		    }  
		
	*/
	
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			SharedPreferences settings = PreferenceManager
					.getDefaultSharedPreferences(this);
			Boolean rememberUser = settings.getBoolean(
					"REMEMBER_USER", true);
			if (!rememberUser) {
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("webip", "");
				
				editor.commit();
			}

			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}
